最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - webpack2 'Can't resolve assetsimgcoin.png' in 'project' - Stack Overflow

programmeradmin5浏览0评论

I'm trying to import an image dynamically with a require statement, but even before that, regular imports like so don't work:

import 'assets/img/coin.png'

The actual use case is:

require(assets/img/${source}.${ext}/);

errors from the import

ERROR in ./app/ponents/Img/index.js
Module not found: Error: Can't resolve 'assets/img/coin.png' in '/Users/rublev/dev/pany/support/app/ponents/Img'
 @ ./app/ponents/Img/index.js 36:0-33
 @ ./app/ponents/SectionList/index.js
 @ ./app/pages/Support/index.js
 @ ./app/views.js
 @ ./app/app.js
 @ multi (webpack)-dev-server/client?:8080 webpack/hot/dev-server webpack-dev-server/client?http://localhost:8080 webpack/hot/only-dev-server ./app/app.js

dir structure

.
├── app
│   ├── app.js
│   ├── assets
│   │   ├── img        <- where i want to import images from
│   ├── ponents
│   │   ├── Footer
│   │   ├── Img        <- ponent im importing images into
│   │   ├── List
│   │   ├── Loader
│   │   ├── Nav
│   │   ├── Searchbar
│   │   ├── SectionList
│   │   └── Vote
│   ├── containers
│   │   └── App
│   ├── index.html
│   ├── pages
│   │   ├── Article
│   │   ├── Section
│   │   └── Support
│   ├── reducers.js
│   ├── router.js
│   ├── store.js
│   └── views.js
├── config
│   ├── webpack.config.base.babel.js
│   ├── webpack.config.development.babel.js
│   └── webpack.config.production.babel.js
├── package.json
└── yarn.lock

webpack.config.base.babel.js

import webpack, { IgnorePlugin } from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { resolve, join } from 'path';

// dotenv
const Dotenv = require('dotenv-webpack');

const NODE_ENV = process.env.NODE_ENV;

const env = {
    production: NODE_ENV === 'production',
    staging: NODE_ENV === 'staging',
    test: NODE_ENV === 'test',
    development: NODE_ENV === 'development' || typeof NODE_ENV === 'undefined'
};

Object.assign(env, {
    build: (env.production || env.staging)
});

export default {
    output: {
        path: join(process.cwd(), '/dist'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    resolve: {
        modules: [
            'node_modules',
            'app',
            join(__dirname, '')
        ],
        extensions: ['.html', '.json', '.scss', '.js', '.jsx'],
        alias: {
            normalize: join(process.cwd(), '/node_modules/normalize-css/normalize.css')
        }
    },
    module: {
        noParse: /\.min\.js/,
        rules: [
            {
                test: /\.json($|\?)/,
                use: 'json-loader',
                enforce: 'pre'
            },
            {
                test: /\.woff|\.woff2|\.svg|.eot|\.ttf/,
                use: 'url-loader?prefix=font/&limit=10000'
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                use: 'file-loader',
                options: {
                    context: '/',
                    name: '[name].[ext]'
                },
            }
        ]
    },
    plugins: ([
        new HtmlWebpackPlugin({
            title: 'pany',
            template: join(process.cwd(), '/app/index.html')
        }),
        new Dotenv(),
        new webpack.DefinePlugin({
            __DEV__: env.development,
            __STAGING__: env.staging,
            __PRODUCTION__: env.production,
            __CURRENT_ENV__: '\'' + (NODE_ENV) + '\''
        })
    ]),
    devServer: {}
};

webpack.config.development.babel.js

import webpack, { IgnorePlugin } from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { resolve, join } from 'path';

import config from './webpack.config.base.babel.js';

if (process.env.NODE_ENV !== 'test') {
    config.entry = [
        'webpack-dev-server/client?http://localhost:8080',
        'webpack/hot/only-dev-server',
        join(process.cwd(), '/app/') + 'app.js'
    ];
}

config.devtool = '#source-map';

config.module.rules = config.module.rules.concat([
    {
        enforce: 'pre',
        test: /\.jsx?$/,
        exclude: resolve(__dirname, 'app', 'node_modules'),
        use: 'source-map-loader'
    },
    {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: 'babel-loader'
    },
    {
        test: /\.css?$/,
        use: [
            'style-loader',
            'css-loader'
        ]
    },
    {
        test: /\.(sass|scss)$/,
        use: [
            'style-loader',
            'css-loader',
            'sass-loader'
        ]
    }
]);

config.devServer = {
    contentBase: './dist',
    host: '0.0.0.0',
    port: 8080,
    stats: {
        version: false,
        chunks: false,
        assets: true,
        colors: true,
        children: true
    }
};

export default config;

I'm trying to import an image dynamically with a require statement, but even before that, regular imports like so don't work:

import 'assets/img/coin.png'

The actual use case is:

require(assets/img/${source}.${ext}/);

errors from the import

ERROR in ./app/ponents/Img/index.js
Module not found: Error: Can't resolve 'assets/img/coin.png' in '/Users/rublev/dev/pany/support/app/ponents/Img'
 @ ./app/ponents/Img/index.js 36:0-33
 @ ./app/ponents/SectionList/index.js
 @ ./app/pages/Support/index.js
 @ ./app/views.js
 @ ./app/app.js
 @ multi (webpack)-dev-server/client?http://0.0.0.0:8080 webpack/hot/dev-server webpack-dev-server/client?http://localhost:8080 webpack/hot/only-dev-server ./app/app.js

dir structure

.
├── app
│   ├── app.js
│   ├── assets
│   │   ├── img        <- where i want to import images from
│   ├── ponents
│   │   ├── Footer
│   │   ├── Img        <- ponent im importing images into
│   │   ├── List
│   │   ├── Loader
│   │   ├── Nav
│   │   ├── Searchbar
│   │   ├── SectionList
│   │   └── Vote
│   ├── containers
│   │   └── App
│   ├── index.html
│   ├── pages
│   │   ├── Article
│   │   ├── Section
│   │   └── Support
│   ├── reducers.js
│   ├── router.js
│   ├── store.js
│   └── views.js
├── config
│   ├── webpack.config.base.babel.js
│   ├── webpack.config.development.babel.js
│   └── webpack.config.production.babel.js
├── package.json
└── yarn.lock

webpack.config.base.babel.js

import webpack, { IgnorePlugin } from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { resolve, join } from 'path';

// dotenv
const Dotenv = require('dotenv-webpack');

const NODE_ENV = process.env.NODE_ENV;

const env = {
    production: NODE_ENV === 'production',
    staging: NODE_ENV === 'staging',
    test: NODE_ENV === 'test',
    development: NODE_ENV === 'development' || typeof NODE_ENV === 'undefined'
};

Object.assign(env, {
    build: (env.production || env.staging)
});

export default {
    output: {
        path: join(process.cwd(), '/dist'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    resolve: {
        modules: [
            'node_modules',
            'app',
            join(__dirname, '')
        ],
        extensions: ['.html', '.json', '.scss', '.js', '.jsx'],
        alias: {
            normalize: join(process.cwd(), '/node_modules/normalize-css/normalize.css')
        }
    },
    module: {
        noParse: /\.min\.js/,
        rules: [
            {
                test: /\.json($|\?)/,
                use: 'json-loader',
                enforce: 'pre'
            },
            {
                test: /\.woff|\.woff2|\.svg|.eot|\.ttf/,
                use: 'url-loader?prefix=font/&limit=10000'
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                use: 'file-loader',
                options: {
                    context: '/',
                    name: '[name].[ext]'
                },
            }
        ]
    },
    plugins: ([
        new HtmlWebpackPlugin({
            title: 'pany',
            template: join(process.cwd(), '/app/index.html')
        }),
        new Dotenv(),
        new webpack.DefinePlugin({
            __DEV__: env.development,
            __STAGING__: env.staging,
            __PRODUCTION__: env.production,
            __CURRENT_ENV__: '\'' + (NODE_ENV) + '\''
        })
    ]),
    devServer: {}
};

webpack.config.development.babel.js

import webpack, { IgnorePlugin } from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { resolve, join } from 'path';

import config from './webpack.config.base.babel.js';

if (process.env.NODE_ENV !== 'test') {
    config.entry = [
        'webpack-dev-server/client?http://localhost:8080',
        'webpack/hot/only-dev-server',
        join(process.cwd(), '/app/') + 'app.js'
    ];
}

config.devtool = '#source-map';

config.module.rules = config.module.rules.concat([
    {
        enforce: 'pre',
        test: /\.jsx?$/,
        exclude: resolve(__dirname, 'app', 'node_modules'),
        use: 'source-map-loader'
    },
    {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: 'babel-loader'
    },
    {
        test: /\.css?$/,
        use: [
            'style-loader',
            'css-loader'
        ]
    },
    {
        test: /\.(sass|scss)$/,
        use: [
            'style-loader',
            'css-loader',
            'sass-loader'
        ]
    }
]);

config.devServer = {
    contentBase: './dist',
    host: '0.0.0.0',
    port: 8080,
    stats: {
        version: false,
        chunks: false,
        assets: true,
        colors: true,
        children: true
    }
};

export default config;
Share Improve this question asked May 2, 2017 at 19:08 eveoeveo 2,85315 gold badges65 silver badges99 bronze badges 2
  • I'd try a leading forward slash and/or setting the resolve.modules config, although in theory it shouldn't be necessary – mikeapr4 Commented May 2, 2017 at 19:30
  • What is the expected value of ${source} and ${ext}on runtime? – Andrea Carraro Commented May 3, 2017 at 11:27
Add a ment  | 

3 Answers 3

Reset to default 2

From your error log, can be seen that webpack is trying to resolve your image require from /Img folder.

Module not found: Error: Can't resolve 'assets/img/coin.png' in '/Users/rublev/dev/pany/support/app/ponents/Img'

Your webpack configuration is telling Webpack to resolve the requires paths trying the following paths (in order):

  • node_modules
  • app
  • The folder where the required is executed

Since the path assets/img/coin.png couldn't be resolved neither in node_modules nor in app directory, Webpack tried to resolve from the last fallback directory and casted the not found error from there.

Is coin.png available in app/assets/img/?

You need to go up two dir levels. Instead of assets/img/coin.png, import ../../assets/img/coin.png.

It turns out Sketch.app exported the files with a space before the filename.

发布评论

评论列表(0)

  1. 暂无评论